import { defineStore } from 'pinia'

// 示例：用户信息 store
export const useUserStore = defineStore('user', {
  state: () => ({
    id: null as string | number | null,
    nickname: '',
    email: '',
    password: '',
    birthday: '',
    gender: '',
    bio: '',
    LuojiaAccount: '',
    avatar: '', // 新增头像字段
    token: '', // 新增token字段
  }),
  actions: {
    setUser(payload: {
      id?: string | number,
      nickname: string,
      email?: string,
      password?: string,
      birthday: string,
      gender: string,
      bio: string,
      avatar?: string,
      token?: string
    }) {
      this.id = payload.id || '';
      this.nickname = payload.nickname;
      this.email = payload.email || '';
      this.password = payload.password || '';
      this.birthday = payload.birthday;
      this.gender = payload.gender;
      this.bio = payload.bio;
      this.avatar = payload.avatar || '';
      this.token = payload.token || '';
      console.log('[Pinia] 用户信息已存入store:', { ...payload });
    },
    /**
     * 信息修改函数：用于更新用户的昵称、生日、性别、简介
     */
    updateUserInfo(payload: {
      nickname?: string,
      birthday?: string,
      gender?: string,
      bio?: string,
      avatar?: string
    }) {
      if (payload.nickname !== undefined) this.nickname = payload.nickname;
      if (payload.birthday !== undefined) this.birthday = payload.birthday;
      if (payload.gender !== undefined) this.gender = payload.gender;
      if (payload.bio !== undefined) this.bio = payload.bio;
      if (payload.avatar !== undefined) this.avatar = payload.avatar;
      console.log('[Pinia] 用户信息已更新:', { ...payload });
    },

    updatePassword(payload: {
      newPassword: string,
    }) {
      this.password = payload.newPassword;
      console.log('[Pinia] 用户密码已更新:', { newPassword: payload.newPassword });
    },
    /**
     * 退出登录，清除所有用户信息
     */
    logout() {
      this.id = null;
      this.nickname = '';
      this.email = '';
      this.password = '';
      this.birthday = '';
      this.gender = '';
      this.bio = '';
      this.LuojiaAccount = '';
      this.avatar = '';
      this.token = '';
      // 可选：清除本地存储的token等
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      console.log('[Pinia] 用户已退出登录，信息已清空');
    },
  },
  persist: true
})
